let pageSize = 2;//当前显示的记录数量
let table_div = document.querySelector("#table_div");
let table = document.createElement("table");
table_div.appendChild(table);
//会覆盖原来的样式
table.className = "table table-hover table-bordered";
// table.classList

let thead = document.createElement("thead");
table.appendChild(thead);
let tbody = document.createElement("tbody");
table.appendChild(tbody);

let tr = document.createElement("tr");
thead.appendChild(tr);
let titles = ["<input name='cb_select_all' type='checkbox'>", "序号", "书名", "日期", "单价", "数量", "操作"];
titles.forEach(function (value, index) {
    let th = document.createElement("th");
    tr.appendChild(th);
    th.innerHTML = value;
    // th.className = "text-center";
    th.classList.add("text-center");
    // th.style.css属性  = css属性值，一般不用
});

let books = [
    {id: 1, name: 'Java从入门到放弃', price: 80, tdate: '2020-07-01', count: 1, email: "haha"},
    {id: 2, name: 'Vue从入门到放弃', price: 90, tdate: '2020-07-02', count: 1, email: "haha"},
    {id: 3, name: 'Mysql从入门到放弃', price: 100.01, tdate: '2020-07-03', count: 1, email: "haha"},
    {id: 4, name: '啥都从入门到放弃', price: 70.0001, tdate: '2020-07-04', count: 1, email: "hehe"},
    {id: 5, name: 'JavaScript从入门到放弃', price: 60.00, tdate: '2020-07-04', count: 1, email: "hehe"},
    {id: 6, name: 'JavaScript从入门到放弃', price: 50.00, tdate: '2020-07-04', count: 1, email: "hehe"}
];

let loginEmail = sessionStorage.getItem("email");
books = books.filter(value => value.email == loginEmail);

function updateTable(array) {
    console.log(array);
    if (!Array.isArray(array)) {
        throw new Error("array 必须是一个数组");
    }

    array.forEach(function (value, index) {
        tr = document.createElement("tr");
        tr.index = index;
        tr["data-id"] = value.id;
        tbody.appendChild(tr);
        let tds = `
            <td><input id="${value.id}" name="cb_select" type="checkbox"></td>
            <td><span>${value.id}</span></td>
            <td editable><span>${value.name}</span><input type="text" name="name" value="${value.name}" hidden></td>
            <td editable><span>${moment(value.tdate).format("YYYY-MM-DD")}</span><input type="date" hidden name="tdate" value="${moment(value.tdate).format("YYYY-MM-DD")}"></td>
            <td editable><span>${value.price}</span><input type="number" name="price" hidden value="${value.price}"></td>
            <td editable>
                <button type="button" onclick="mouse(event)">-</button>
                <span>${value.count}</span>
                <button type="button" onclick="add(event)">+</button>
                <input type="number" name="count" hidden value="${value.count}">
            </td>
            <td>
                <button type="button" onclick="edit(event)">编辑</button>
                <button type="button" onclick="del(event)">删除</button>
            </td>
        `;
        tr.innerHTML = tds;
    });

    let tds = document.querySelectorAll("tbody tr td");
    // console.log(tds);
    Array.from(tds).forEach(function (value) {
        //不会覆盖原来的样式
        value.classList.add("text-center");
    });
}

function insert(event) {
    let addTr = `
            <tr>
                <td><input type="checkbox"></td>
                <td></td>
                <td><input type="text" name="name" placeholder="书名"></td>
                <td><input type="date" name="tdate" placeholder="日期"></td>
                <td><input type="number" name="price" placeholder="单价"></td>
                <td>
                    <input type="number" name="count" placeholder="数量">
                </td>
                <td>
                    <button type="button" onclick="save(event)">保存</button>
                    <button type="button">取消</button>
                </td>
            </tr>
        `;
    table.querySelector("tbody").insertAdjacentHTML("afterend", addTr);
}

function edit(event) {
    let self = event.target;
    let editTr = self.parentNode.parentNode;
    let tds = editTr.querySelectorAll("td[editable]");
    console.log(tds);
    if (self.innerText == "编辑") {
        tds.forEach(value => {
            value.querySelector("span").hidden = true;
            value.querySelector("input").hidden = false;
            if (value.querySelectorAll("button").length > 0) {
                value.querySelectorAll("button").forEach(btn => {
                    btn.hidden = true;
                });
            }
        });
        self.innerText = "保存";
    } else {
        save(event, newObj => {
            let dataId = editTr["data-id"];
            console.log(`dataId: ${dataId}`);
            let editIndex;
            books.forEach((value, index) => {
               if (value.id == dataId) {
                   editIndex = index;
               }
            });
            let editObj = books[editIndex];
            newObj.id = editObj.id;
            books.splice(editIndex, 1, newObj);
        });
        // self.innerText = "编辑";
    }
}

function save(event, callback) {
    let self = event.target;
    let editTr = self.parentNode.parentNode;
    let inputs = editTr.querySelectorAll("input");
    // let newObj = {
    //     name: inputs[1.txt].value,
    //     price: input[2].value
    // };
    let newObj = {};//要保存的数据内容
    inputs.forEach(value => {
        console.log(value);
        if (value.type != "checkbox") {
            if (value.type == "number") {
                newObj[value.name] = value.valueAsNumber;
            } else if (value.type == "date") {
                newObj[value.name] = value.valueAsDate;
            } else {
                newObj[value.name] = value.value;
            }
        }
    });
    if (callback) {
        callback(newObj);
    } else {
        newObj.id = getInsertId(books);
        console.log(newObj);
        //保存到数组中
        books.push(newObj);
    }
    //刷新表格
    pagination(books, 1);
}

function add(event) {
    console.log("add");
    let self = event.target;
    let span = self.previousElementSibling;
    // console.log(span);
    let tr = self.parentNode.parentNode;
    let count = parseInt(span.innerText) + 1;
    span.innerText = count;
    books[getIndexById(books, tr["data-id"])].count = count;
    // console.log(books);
    calTotal(books);
}

/**
 * 根据id从books数组寻找索引
 * @param array
 * @param id
 * @returns {*}
 */
function getIndexById(array, id) {
    let editIndex;
    array.forEach((value, index) => {
        if (value.id == id) {
            editIndex = index;
        }
    });

    return editIndex;
}

function mouse(event) {
    console.log("mouse");
    let self = event.target;
    let span = self.nextElementSibling;
    let count;
    if (parseInt(span.innerText) <= 0) {
        count = 0;
    } else {
        count = parseInt(span.innerText) - 1;
    }
    span.innerText = count;

    let tr = self.parentNode.parentNode;
    books[getIndexById(books, tr["data-id"])].count = count;
    // console.log(books);
    calTotal(books);
}

function clearTable() {
    Array.from(table.tBodies).forEach(value => {
        while (value.hasChildNodes()) {
            value.firstChild.remove();
        }
    })
}

function getInsertId(array) {
    if (!Array.isArray(array)) {
        throw new Error("array 必须是一个数组");
    }

    let maxId = array[0].id;
    array.forEach(value => {
        if (maxId < value.id) {
            maxId = value.id;
        }
    });

    return maxId + 1;
}

let cb_select_all = document.querySelector("input[name='cb_select_all']");
cb_select_all.onchange = function (event) {
    let self = event.target;
    console.log(self.checked);
    let cb_selects = table.querySelectorAll("input[name='cb_select']");
    cb_selects.forEach((value, index) => {
        value.checked = self.checked;
    });
}

function delBatch(event) {
    let cb_selects = table.querySelectorAll("input[name='cb_select']");
    cb_selects.forEach((value, index) => {
        if (value.checked) {
            // let editTr = value.parentNode.parentNode;
            // delete books[editTr.index];
            let id = value.id;//数据的id属性
            books.forEach((item, itemIndex) => {
                if (item.id == id) {
                    books.splice(itemIndex, 1);
                }
            });
            console.log(books);
        }
    });
    //刷新表格
    pagination(books, 1);
}

function del(event) {
    let self = event.target;
    let editTr = self.parentNode.parentNode;

    let result = confirm(`是否删除id为${books[editTr.index].id}的数据`);
    if (result) {
        // editTr.remove();
        // console.log(editTr.index);
        // console.log(editTr["data-id"]);
        books.forEach((value, index) => {
            if (editTr["data-id"] == value.id) {
                books.splice(index, 1);
            }
        });
        // console.log(books);
        //刷新表格
        pagination(books, 1);
    }
}

function search(self) {
    // event.stopPropagation();//终止事件冒泡
    let form = self.form;
    // console.log(self);
    // console.log(form);
    let input_name = form["name"];
    let input_min_price = form["minPrice"];
    let input_max_price = form["maxPrice"];

    let name = input_name.value;
    let min_price = input_min_price.valueAsNumber;
    let max_price = input_max_price.valueAsNumber;
    let filterBooks = books;
    //书名搜索
    if (name.trim().length > 0) {
        filterBooks = filterBooks.filter((value, index, array) => {
            //搜索，精确匹配，模糊匹配
            // if (name.trim() == value.name.trim()) {
            //
            // }
            if (value.name.toLowerCase().indexOf(name.trim().toLowerCase()) != -1) {
                return true;
            }

            return false;
        });
    }
    //最低价
    if (!isNaN(min_price)) {
        filterBooks = filterBooks.filter((value, index, array) => {
            if (value.price >= min_price) {
                return true;
            }

            return false;
        });
    }
    //最高价
    if (!isNaN(max_price)) {
        filterBooks = filterBooks.filter((value, index, array) => {
            if (value.price <= max_price) {
                return true;
            }

            return false;
        });
    }
    console.log(filterBooks);
    //刷新表格
    pagination(filterBooks, 1);
}

function clear(tag) {
    if (tag instanceof Node) {
        while (tag.hasChildNodes()) {
            tag.firstChild.remove();
        }
    }
}

function pagination(array, pageNum = 1) {
    if (!Array.isArray(array)) {
        throw new Error("array 必须是一个数组");
    }

    // let pageSize = 2;//每页显示的数据量
    let total = array.length;//数据总数

    let page_total = document.querySelector("#page_total");
    page_total.textContent = `一共${total}条记录`;
    let page_select = document.querySelector("#page_select");
    page_select.onchange = function (event) {
        pageSize = parseInt(page_select.value);
        pagination(array, pageNum);
    };

    let pageCount;//一共有多少页
    if (total % pageSize === 0) {
        pageCount = Math.floor(total / pageSize);
    } else {
        pageCount = Math.floor(total / pageSize) + 1;
    }
    // let pageNum = 0;//当前页码
    let firstNum = 1;//首页码1
    let lastNum = pageCount;//尾页码
    let preNum = pageNum - 1;//上一页页码
    if (preNum <= 0) {
        preNum = 0;
    }
    let nextNum = pageNum + 1;//下一页页码
    if (nextNum >= pageCount) {
        nextNum = pageCount;
    }

    let pagination_ul = document.querySelector(".pagination");
    clear(pagination_ul);
    let pos = "beforeend";
    //首页
    let li;
    li = document.createElement("li");
    li.className = pageNum == firstNum ? "disabled" : "";
    li.innerHTML = `
        <a href="javascript:void(0);">
            <span>首页</span>
        </a>
    `;
    li.onclick = function () {
        pagination(array, firstNum);
    };
    pagination_ul.insertAdjacentElement(pos, li);
    //上一页
    li = document.createElement("li");
    li.className = pageNum == firstNum ? "disabled" : "";
    li.innerHTML = `
        <a href="javascript:void(0);">
            <span>上一页</span>
        </a>
    `;
    li.onclick = function () {
        pagination(array, preNum);
    };
    pagination_ul.insertAdjacentElement(pos, li);
    //中间的页码
    for (let i = 1; i <= pageCount; i++) {
        li = document.createElement("li");
        li.className = i == pageNum ? "active" : "";
        li.innerHTML = `
        <a href="javascript:void(0);">
            <span>${i}</span>
        </a>
    `;
        li.onclick = function () {
            pagination(array, i);
        };
        pagination_ul.insertAdjacentElement(pos, li);
    }
    //下一页
    li = document.createElement("li");
    // console.log("pageCount:" + pageCount);
    // console.log("pageNum:" + pageNum);
    // console.log(`lastNum：${lastNum}`);
    // console.log(`nextNum：${nextNum}`);
    // console.log(`preNum：${preNum}`);
    li.className = pageNum == lastNum ? "disabled" : "";
    li.innerHTML = `
        <a href="javascript:void(0);">
            <span>下一页</span>
        </a>
    `;
    li.onclick = function () {
        pagination(array, nextNum);
    };
    pagination_ul.insertAdjacentElement(pos, li);
    //尾页
    li = document.createElement("li");
    li.className = pageNum == lastNum ? "disabled" : "";
    li.innerHTML = `
        <a href="javascript:void(0);">
            <span>尾页</span>
        </a>
    `;
    li.onclick = function () {
        pagination(array, lastNum);
    };
    // li.addEventListener("click", function () {
    //     pagination(array, pageCount);
    // });
    pagination_ul.insertAdjacentElement(pos, li);

    clearTable();
    updateTable(array.filter((value, index) => {
        return index < pageSize * pageNum && index >= pageSize * (pageNum - 1);
    }));
    calTotal(array);
}

pagination(books, 1);

function calTotal(array) {
    let total = array.reduce(function (pre, cur) {
        return pre + cur.price * cur.count;
    }, 0);
    let total_price = document.querySelector("#total_price");
    total_price.textContent = "￥" + total.toFixed(2);
}
